package com.contact.util.util.spring;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import com.contact.util.ResourceRetriever;

public final class SpringResourceRetriever implements ResourceRetriever {

	private transient final ResourceLoader loader = new DefaultResourceLoader();

	@Override
	public InputStream getResourceAsStream(String name) throws IOException {
		// 1st way
		// return ClassPathResource resource = new ClassPathResource(name);
		// return resource.getInputStream();
		// 2nd way
		Resource resource = loader.getResource(name);
		if (resource == null) {
			throw new IOException("Resource not found in classpath: " + name);
		}
		return resource.getInputStream();

	}

	public String convertStreamToString(InputStream is) throws IOException {
		// found at http://www.kodejava.org/examples/266.html
		// slightly modified
		/*
		 * To convert the InputStream to String we use the BufferedReader.readLine()
		 * method. We iterate until the BufferedReader return null which means
		 * there's no more data to read. Each line will appended to a StringBuilder
		 * and returned as String.
		 */
		if (is == null) {
			return "";
		}

		StringBuilder sb = new StringBuilder();
		String line;

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			while ((line = reader.readLine()) != null) {
				sb.append(line).append("\n");
			}
		} finally {
			is.close();
		}
		return sb.toString();
	}

	@Override
	public Map<String, String> getPropertyResource(String name) throws IOException {
        return null;
		/*MapReader mapReader = new MapReader();
		InputStream is = getResourceAsStream(name);
		return mapReader.readMap(is);*/
	}

}
